<template>
  <a-card title="Project Hours Distribution" class="project-chart">
    <div ref="chartRef" style="height: 400px;"></div>
  </a-card>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  workOrders: {
    type: Array,
    required: true
  }
});

const chartRef = ref(null);
let chartInstance = null;

const processChartData = (workOrders) => {
  const projectMap = {};
  
  workOrders.forEach(order => {
    if (!projectMap[order.project]) {
      projectMap[order.project] = 0;
    }
    projectMap[order.project] += order.hours;
  });
  
  return {
    projects: Object.keys(projectMap),
    hours: Object.values(projectMap)
  };
};

const initChart = () => {
  if (!chartRef.value) return;
  
  chartInstance = echarts.init(chartRef.value);
  updateChart();
};

const updateChart = () => {
  const { projects, hours } = processChartData(props.workOrders);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: projects,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '工时（小时）'
    },
    series: [
      {
        name: '工时',
        type: 'bar',
        data: hours,
        itemStyle: {
          color: '#1890ff'
        },
        label: {
          show: true,
          position: 'top'
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '10%',
      containLabel: true
    }
  };
  
  if (chartInstance) {
    chartInstance.setOption(option);
  }
};

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});

watch(() => props.workOrders, () => {
  updateChart();
}, { deep: true });

watch(chartRef, () => {
  if (chartRef.value) {
    initChart();
  }
});
</script>

<style lang="less" scoped>
.project-chart {
  margin-bottom: 24px;
}
</style>